package service

import (
	"github.com/gin-gonic/gin"
	"wx_build/core/msg"
	"wx_build/global"
	"wx_build/model/tables"
	"wx_build/utils"
)

type TaskService struct {
	tables.Task
	Page   int    `json:"page"`
	Size   int    `json:"size"`
	Search string `json:"search"`
}

func (c *TaskService) List(g *gin.Context) {
	list := new([]tables.Task)
	var count int64
	db := global.Sqlite
	if c.Search != "" {
		projectList := new([]tables.Project)
		db.Where("project_name LIKE ?", "%"+c.Search+"%").Find(&projectList)
		var projectIds []string
		for _, v := range *projectList {
			projectIds = append(projectIds, v.ProjectId)
		}
		db = db.Where("project_id in (?)", projectIds)
	}
	db.Where(c.Task).Find(&list).Count(&count)
	db.Where(c.Task).Order("created_at desc").Limit(c.Size).Offset((c.Page - 1) * c.Size).Find(&list)
	data := make([]map[string]interface{}, len(*list))
	for k, v := range *list {
		item, _ := utils.ToMap(v)
		item["project_info"] = c.getProjectInfo(v.ProjectId)
		data[k] = item
	}
	res := make(map[string]interface{})
	res["list"] = data
	res["count"] = count
	msg.Success(g, "查询成功", res)
	return
}
func (c *TaskService) getProjectInfo(projectId string) map[string]interface{} {
	project := tables.Project{
		ProjectId: projectId,
	}
	project.QueryOne(&project)
	res, _ := utils.ToMap(project)
	return res
}
